<?php

namespace app\api\controller\wanlshop;

use addons\wanlshop\library\WanlSdk\Common;
use app\admin\model\shopro\Category;
use app\admin\model\wanlshop\AddressSpot;
use app\admin\model\wanlshop\QrcodeLog;
use app\api\model\wanlshop\Goods;
use app\api\model\wanlshop\GoodsSku;
use app\api\model\wanlshop\Industry;
use app\api\model\wanlshop\OrderGoods;
use app\common\controller\Api;
use fast\Tree;
use think\Db;
//use Endroid\QrCode\Builder\Builder;
//use Endroid\QrCode\Encoding\Encoding;
//use Endroid\QrCode\ErrorCorrectionLevel;
//use Endroid\QrCode\Label\LabelAlignment;
//use Endroid\QrCode\Label\Font\NotoSans;
//use Endroid\QrCode\RoundBlockSizeMode;
//use Endroid\QrCode\Writer\PngWriter;
use phpqrcode\QRcode;
/**
 * WanlShop产品接口
 */
class Product extends Api
{
	protected $noNeedLogin = ['category','lists', 'goods', 'drawer', 'comment', 'likes', 'stock','industry','groupsList','buyGroupList','offShelf'];
	protected $noNeedRight = ['*'];

	protected $excludeFields = "";

    /**
     * 获取商品列表 1.0.3升级 隐藏查询结果 1.0.4升级 错误查询
     *
     * @ApiSummary  (WanlShop 产品接口获取商品列表)
     * @ApiMethod   (GET)
	 *
	 */
    public function lists($type = 'goods')
    {
    	//设置过滤方法
    	$this->request->filter(['strip_tags']);
		// 判断业务类型
		if($type === 'goods' || $type === 'newGroups'){
			$goodsModel  = model('app\api\model\wanlshop\Goods');
		}else if($type === 'groups'){
			$goodsModel  = model('app\api\model\wanlshop\groups\Goods');
		}

    	// 生成搜索条件
    	list($where, $sort, $order) = $this->buildparams('title,category.name',true,'goods'); // 查询标题 和类目字段  ！！！！！！排除已下架//-------------------------------------------
        $shopIdFiltered = false;
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];
        if (isset($filter['shop_id']) && !empty($filter['shop_id'])) {
            $shopIdFiltered = true;
        }
        // 查询数据
    	$list = $goodsModel
            ->alias('goods')
    		->with(['shop','category'])
            ->where($where)
			->where('goods.status', 'normal')
    	    ->order($sort, $order);
        if (!$shopIdFiltered) {
            $list->where('activity_type', '<>', 'newGroups');
        }
        if($type == 'newGroups'){
            $list->where('activity_type',$type);
        }

        $list = $list->paginate();
    	foreach ($list as $row) {
            $row['id'] = (string)$row['id'];
    	    $row->getRelation('shop')->visible(['city', 'shopname', 'state', 'isself']);
    		$row->getRelation('category')->visible(['id','pid','name']);
    		$row->isLive = model('app\api\model\wanlshop\Live')->where(['shop_id' => $row['shop_id'], 'state' => 1])->field('id')->find();
    	}
    	$this->success('返回成功', $list);
    }

	/**
	 * 搜索获取品牌列表
	 *
	 * @ApiSummary  (WanlShop 产品接口获取品牌列表)
	 * @ApiMethod   (GET)
	 *
	 */
	public function drawer($type = 'goods')
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$search = $this->request->request("search"); // 查询商品品牌
		$id = $this->request->request("category_id"); // 查询类目品牌
		// 判断业务类型
		if($type === 'goods'){
			$goodsModel  = model('app\api\model\wanlshop\Goods');
		}else if($type === 'groups'){
			$goodsModel  = model('app\api\model\wanlshop\groups\Goods');
		}
		$brandModel = model('app\api\model\wanlshop\Brand');
		$attributeModel  = model('app\api\model\wanlshop\Attribute');

		// 1.0.8升级  获取父级类目属性
		$category_id = null;
		$attribute_ids = null;
		$tree = Tree::instance();
		$tree->init(collection(model('app\index\model\wanlshop\Category')->select())->toArray(), 'pid');

		// 直接查询类目
		if($id){
			$category_id = $id;
			$attribute_ids = $tree->getParentsIds($id, true);
		}
		// 通过商品类目查询
		if($search){
			$ids = [];
			foreach ($goodsModel->where('title', 'like', '%'.$search.'%')->where('activity_type','<>','newGroups')->select() as $row) {
				$ids[] = $row['category_id'];
			}
			$ids = array_flip($ids);
			$category_ids = '';
			foreach ($ids as $key => $value){
			    $category_ids .= implode(',', $tree->getParentsIds($key, true)).',';
			}
			$category_id = array_keys($ids);
			$attribute_ids = array_keys(array_flip(explode(',', rtrim($category_ids, ','))));
		}
		// 返回数据
		$this->success('返回成功', [
			'brand' => $brandModel
				->where('category_id', 'in', $category_id)
				->where('status','normal')
				->field('name')
				->select(),
			'attribute' => $attributeModel
				->where('category_id', 'in', $attribute_ids)
				->where('status','normal')
				->field('name,value')
				->select()
		]);
	}

	/**
	 * 猜你喜欢
	 *
	 * @ApiSummary  (WanlShop 猜你喜欢)
	 * @ApiMethod   (GET)
	 *
	 * @param string $pages 页面ID
	 * @param string $category_id 类目ID
	 */
	public function likes()
	{
		$pages = $this->request->request('pages'); //不同页面不同排序,goods只获得与当前产品相同类目,index获得排名靠前的,user随意获取
		$category_id = $this->request->request('cid');
		// 判断来源
		if($pages == 'index'){
			$sort = 'payment';
		}else if($pages == 'user'){
			$sort = 'comment';
		}else if($pages == 'cart'){
			$sort = 'views';
		}else if($pages == 'goods'){
			$sort = 'weigh';
		}else{
			$sort = 'like';
		}
		$uuid = $this->request->server('HTTP_UUID');
		if(!isset($uuid)){
			$charid = strtoupper(md5($this->request->header('user-agent').$this->request->ip()));
			$uuid = substr($charid, 0, 8).chr(45).substr($charid, 8, 4).chr(45).substr($charid,12, 4).chr(45).substr($charid,16, 4).chr(45).substr($charid,20,12);
		}
		// 统计
		$record = model('app\api\model\wanlshop\Record')->where(['uuid'=>$uuid]);
		// 获取上架商品 1.0.3升级
		$where['status'] = 'normal';
		//如果没有
		if($record->count() == 0){
			if($category_id){
				$category_pid = model('app\api\model\wanlshop\Category')->get($category_id);
				$array = model('app\api\model\wanlshop\Category')
					->where(['pid' => $category_pid['pid']])
					->select();
				$cid = [];
				foreach ($array as $value) {
					$cid[] = $value['id'];
				}
				$where['category_id'] = ['in',$cid];
			}
			$goods = model('app\api\model\wanlshop\Goods')
                ->where('activity_type','<>','newGroups')
				->where($where)
				->orderRaw('rand()')
				->field('id,shop_id,title,image,flag,price,views,sales,comment,praise,like,delivery_method')
				->paginate();
		}else{
			$like_cat = array_count_values($record->column('category_pid')); //喜欢的类目
			$like_goods_cat = array($record->order('views', 'desc')->find()['category_pid']); //喜欢产品的类目
			arsort($like_cat); //排序
			$like_cat_top = array_slice(array_keys($like_cat),0,5); //排名前5
			$category_pid = array_intersect($like_cat_top,$like_goods_cat); //是否包含喜欢的产品类目
			// 如果包含输入产品类目,如果不包含输出排名第一的
			if($category_pid){
				$category_pid = array_slice($category_pid,0,1)[0];
			}else{
				$category_pid = $like_cat_top[0];
			}
			// 查询指定
			if($category_id){
				$category_pid = model('app\api\model\wanlshop\Category')->get($category_id)['pid'];
			}
			//查询下级类目
			$array = model('app\api\model\wanlshop\Category')
				->where(['pid' => $category_pid])
				->select();
			$cid = [];
			foreach ($array as $value) {
				$cid[] = $value['id'];
			}
			$where['category_id'] = ['in',$cid];
			// 查询父ID下所有商品
			$goods = model('app\api\model\wanlshop\Goods')
                ->where('activity_type','<>','newGroups')
				->where($where)
				->orderRaw('rand()')
				->field('id,shop_id,title,image,flag,price,views,sales,comment,praise,like,delivery_method')
				->paginate();
		}
		foreach ($goods as $row) {
			$row->shop->visible(['state','shopname']);
			$row->isLive = model('app\api\model\wanlshop\Live')->where(['shop_id' => $row['shop_id'], 'state' => 1])->field('id')->find();
		}
		$this->success('返回成功', $goods);
	}

    /**
     * 获取商品详情
     *
     * @ApiSummary  (WanlShop 产品接口、浏览+1、获取UUID生成访问记录)
     * @ApiMethod   (GET)
     *
     * @param string $id 商品ID
     */
    public function goods()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$id = $this->request->request("id");
		// 是否传入商品ID
		$id ? $id : ($this->error(__('非正常访问')));
		// 加载商品模型
		$goodsModel = model('app\api\model\wanlshop\Goods');
		// 查询商品
		$goods = $goodsModel
			->where(['id' => $id])
//			->field('id,category_id,shop_category_id,brand_id,freight_id,shop_id,title,image,images,flag,content,category_attribute,activity_type,price,sales,payment,comment,praise,moderate,negative,like,views,status')
			->find();

		// 浏览+1 & 报错
		if($goods && $goods['status'] == 'normal'){

		    if($goods->category){
                // 查询类目
                $goods->category->visible(['id','pid','name']);
		    }

			// 查询优惠券
			$goods['coupon'] = $this->queryCoupon($goods['id'], $goods['shop_id'], $goods['shop_category_id'], $goods['price']);
			// 查询是否关注
			$goods['follow'] = $this->isfollow($id);
			// 查询品牌
            if($goods->brand){
                // 查询类目
                $goods->brand->visible(['name']);
            }

			// 查询SKU
			$goods['sku'] = $goods->sku;
			// 查询SPU
			$goods['spu'] = $goods->spu;
			// 查询直播状态
			$goods['isLive'] = model('app\api\model\wanlshop\Live')->where(['shop_id' => $goods['shop_id'], 'state' => 1])->field('id')->find();
			// 查询评论
			$goods['comment_list'] = $goods->comment_list;
			// 获取店铺详情
            if($goods->shop){
                // 查询类目
                $goods->shop->visible(['shopname','service_ids','avatar','city','like','score_describe','score_service','score_logistics','isFollow','id']);


            }

            if($goods['shop']){
                // 查询类目
                $goods['shop']['isFollow'] = model('app\api\model\wanlshop\find\Follow')
                    ->where([
                        'user_no' => $goods->shop['find_user']['user_no'],
                        'user_id' => $this->auth->id
                    ])
                    ->count();
            }

			// 查询快递 运费ID 商品重量 邮递城市 商品数量
			$goods['freight'] = $this->freight($goods['freight_id']);
			// 查询促销
			$goods['promotion'] = $id; //--下个版本更新--
			// 店铺推荐
			$goods['shop_recommend'] = $goodsModel
				->where(['shop_id' => $goods['shop_id'], 'status' => 'normal']) //还可以使用 , 'flag' => 'recommend'
				->field('id,title,image,price')
				->limit(3)
				->select();
			// 浏览+1

			$goods->setInc('views');
            $userModel = model('app\api\model\User');
            $goods['tuanNum'] = $userModel->alias('u')
                ->join('wanlshop_order o', 'u.id = o.user_id')
                ->join('wanlshop_order_goods og', 'o.id = og.order_id')
                ->where('og.goods_id', $goods['id'])
                ->count();
			// 写入访问日志
			$this->addbrowse($goods);

            $data = $this->useScore($goods);
            // 设置使用积分和最终价格
            $goods->useScore = $data['useScore'];
            $goods->oldPrice = $goods->price;
            $goods->price =  $data['price'];
            $goods->id = (string)$goods['id'];
			// 返回结果
			$this->success('返回成功', $goods);
		}else{
			$this->error(__('对不起当前商品不存在或已下架！'));
		}
    }
    //积分不足时是否可以下一步
    public function pointsUse()
    {

        $points = $this->request->post("points");
        $goods_id = $this->request->post("goods_id");
        $price = $this->request->post("price",0);
        $num = $this->request->post("num",1);
        $user = \app\admin\model\User::where('id',$this->auth->id)->find();
        //获取1积分抵扣金额
        $config = get_addon_config('wanlshop');
        $deduct_amount = $config['config']['deduction_amount']; // 1积分抵扣金额
        // 计算实际需要的总积分
        $total_points = $points * $num; // 总积分 = 单件商品积分 * 购买数量
        $total_price = $price * $num; // 商品总金额 = 单件商品价格 * 购买数量
        if($total_points > $user['score']){
            $good = Goods::where('id',$goods_id)->find();
            if($good['is_repair'] == 1){
                // 商品允许用金额抵扣
                $available_points = $user['score']; // 用户可以使用的积分
                $remaining_points = $total_points - $available_points; // 剩余需要的积分
                // 计算需要补充的金额
                $additional_amount = round($remaining_points * $deduct_amount, 2);
                // 计算总需要支付的金额 = 商品总价格 + 需要补充的金额
                $total_amount = round($additional_amount + $total_price, 2);
                $this->success('返回成功', [
                    'available_points' => $available_points,
                    'additional_amount' => number_format($total_amount, 2, '.', ''), // 总支付金额
                    'type' => 1
                ]);
            }else{
                $this->success('返回成功', ['type'=>0]);
            }
        }else{
            // 积分足够的情况，用户使用积分，但仍然需要支付商品总金额
            $this->success('返回成功', [
                'type' => 2,
                'available_points' => $total_points,
                'additional_amount' => number_format($total_price, 2, '.', '') // 商品总金额
            ]);
        }
    }
    public function useScore($goods,$maximum_proportion = 0)
    {
        //获取1积分抵扣金额
        $config = get_addon_config('wanlshop');
        $deduct_amount = $config['config']['deduction_amount']; // 1积分抵扣金额
        // 积分可抵扣金额的百分比
        if($maximum_proportion>0){
            $maximum_proportion = $maximum_proportion / 100;
        }else{
            $maximum_proportion = $goods['maximum_proportion'] / 100;
        }


        // 商品的价格
        $price = $goods['price'];
        // 最大可以使用积分抵扣的金额
        $max_deductible_amount = min($price, $price * $maximum_proportion);
        // 需要使用的积分数 = 最大可抵扣金额 ÷ 每1积分可抵扣的金额
        $required_score = ceil($max_deductible_amount / $deduct_amount);
        // 实际抵扣金额 = 所使用的积分 * 每1积分可抵扣的金额
        $actual_deduct_amount = $required_score * $deduct_amount;
        // 保证抵扣后剩余金额是非负，并保留两位小数
        $remaining_price = number_format($price - $actual_deduct_amount, 2, '.', '');
        $data = [
            'useScore'=>$required_score,
            'price'=>$remaining_price
        ];
        return $data;
    }
	/**
	 * 实时查询库存
	 *
	 * @ApiSummary  (WanlShop 实时查询库存)
	 * @ApiMethod   (GET)
	 *
	 * @param string $sku_id  SKU
	 */
	public function stock($sku_id = '')
	{
		$redis = Common::redis();
		$sku = model('app\api\model\wanlshop\GoodsSku')->get($sku_id);
		$sku_key = 'goods_'.$sku['goods_id'].'_'.$sku['id'];
		// 获取缓存数量
		$llen = $redis->llen("{$sku_key}");
		if(!$llen){
			for ($i = 0; $i < $sku['stock']; $i ++) {
				$redis->lpush("{$sku_key}", 1);
			}
		}
		$this->success('查询成功', $redis->llen("{$sku_key}"));
	}

	/**
	 * 是否关注商品
	 *
	 * @ApiSummary  (WanlShop 保存浏览记录)
	 * @ApiMethod   (GET)
	 *
	 * @param string $goods  商品数据
	 */
	public function isfollow($goods_id ='')
	{
		$data = false;
		if ($this->auth->isLogin()) {
			$follow = model('app\api\model\wanlshop\GoodsFollow')
				->where([
					'user_id' => $this->auth->id,
					'goods_id' => $goods_id,
					'goods_type' => 'goods'
				])
				->count();
			$data = $follow == 0 ? false : true; //关注
		}
		return $data;
	}

	/**
	 * 保存浏览记录
	 *
	 * @ApiSummary  (WanlShop 保存浏览记录)
	 * @ApiMethod   (GET)
	 *
	 * @param string $goods  商品数据
	 */
	public function addbrowse($goods =[])
	{
		//保存浏览记录
		$uuid = $this->request->server('HTTP_UUID');
		if(!isset($uuid)){
			$charid = strtoupper(md5($this->request->header('user-agent').$this->request->ip()));
			$uuid = substr($charid, 0, 8).chr(45).substr($charid, 8, 4).chr(45).substr($charid,12, 4).chr(45).substr($charid,16, 4).chr(45).substr($charid,20,12);
		}
		$recordModel = model('app\api\model\wanlshop\Record');
		$goods_type = 'goods';
		$record = $recordModel
			->where([
				'uuid' => $uuid,
				'goods_id' => $goods['id'],
				'goods_type' => $goods_type
			])
			->find();


		if($record){
			$update['id'] = $record['id'];
			if ($this->auth->isLogin()) {
				$update['user_id'] = $this->auth->id;
			}
			$update['views'] = $record['views'] + 1;
			$record->update($update);

		}else{
			if ($this->auth->isLogin()) {
				$recordModel->user_id = $this->auth->id;
			}

			$recordModel->uuid = $uuid;
			$recordModel->goods_id = $goods['id'];
			$recordModel->goods_type = $goods_type;
			$recordModel->shop_id = $goods['shop_id'];
			$recordModel->category_id = $goods['category']['id'];
			$recordModel->category_pid = $goods['category']['pid'];
			$recordModel->ip = $this->request->ip();
			$recordModel->save();

		}
	}

	/**
	 * 关注商品
	 *
	 * @ApiSummary  (WanlShop 关注或取消商品)
	 * @ApiMethod   (POST)
	 *
	 * @param string $id 商品ID
	 */
	public function follow()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$id = $this->request->post("id");
			// 是否传入商品ID
			$id ? $id : ($this->error(__('非正常访问')));
			// 加载商品模型
			$goodsModel = model('app\api\model\wanlshop\Goods');
			$goodsFollowModel = model('app\api\model\wanlshop\GoodsFollow');
			$data = [
				'user_id' => $this->auth->id,
				'goods_id' => $id,
				'goods_type' => 'goods'
			];
			if($goodsFollowModel->where($data)->count() == 0){
				$goodsFollowModel->save($data);
				$goodsModel->where(['id' => $id])->setInc('like'); //喜欢+1
				$follow = true;
			}else{
				$goodsFollowModel->where($data)->delete();
				$goodsModel->where(['id' => $id])->setDec('like'); //喜欢-1
				$follow = false;
			}
			$this->success('返回成功', $follow);
		}
		$this->error(__('非正常访问'));
	}

	/**
	 * 收藏夹列表 1.0.8升级
	 */
	public function collect($type = 'goods')
	{
		$followIds = [];
		$followModel = model('app\api\model\wanlshop\GoodsFollow');
		// 判断业务类型
		if($type === 'goods'){
			$goodsModel = model('app\api\model\wanlshop\Goods');
			$field = 'id, shop_id, title, image, views, price, sales, payment, like';
		}else if($type === 'groups'){
			$goodsModel = model('app\api\model\wanlshop\groups\Goods');
			$field = 'id, shop_id, title, image, views, price, sales, payment, like, is_ladder, people_num';
		}
		// 获取收藏夹IDS
		foreach ($followModel->where(['user_id' => $this->auth->id, 'goods_type' => $type])->select() as $row) {
			// 排除不存在商品
		    if($goodsModel->get($row['goods_id'])){
				$followIds[] = $row['id'];
			}
		}
		// 按条件查询
		$list = $followModel
			->where('id', 'in', $followIds)
			->field('goods_id')
			->paginate();
		foreach ($list as $row) {
		    $row['goods'] = $goodsModel
				->where(['id' => $row['goods_id']])
				->field($field)
				->find();
		}
		$this->success('返回成功', $list);
	}

	/**
	 * 足迹列表 1.0.8升级
	 */
	public function footprint($type = 'goods')
	{
		$footprintIds = [];
		$recordModel = model('app\api\model\wanlshop\Record');
		// 判断业务类型
		if($type === 'goods'){
			$goodsModel = model('app\api\model\wanlshop\Goods');
		}else if($type === 'groups'){
			$goodsModel = model('app\api\model\wanlshop\groups\Goods');
		}
		// 1.0.8升级  通过uuid查询足迹
		$uuid = $this->request->server('HTTP_UUID');
		if(!isset($uuid)){
			$charid = strtoupper(md5($this->request->header('user-agent').$this->request->ip()));
			$uuid = substr($charid, 0, 8).chr(45).substr($charid, 8, 4).chr(45).substr($charid,12, 4).chr(45).substr($charid,16, 4).chr(45).substr($charid,20,12);
		}
		// 获取足迹IDS
		$record = $recordModel->where(['uuid' => $uuid, 'goods_type' => $type])->select();
		foreach ($record as $row) {
			// 排除不存在商品
		    if($goodsModel->get($row['goods_id'])){
				$footprintIds[] = $row['id'];
			}
		}
		// 按条件查询
		$list = $recordModel
			->where('id', 'in', $footprintIds)
			->field('goods_id, createtime')
			->order('createtime', 'desc')
			->paginate();
		foreach ($list as $row) {
		    $row['goods'] = $goodsModel
				->where(['id' => $row['goods_id']])
				->field('id, image, title, price, payment')
				->find();
		}
		$this->success('返回成功', $list);
	}

	/**
	 * 查询用户指定店铺浏览记录
	 *
	 * @ApiSummary  (查询用户指定店铺浏览记录 1.0.2升级)
	 * @ApiMethod   (POST)
	 *
	 * @param string $shop_id 店铺ID
	 */
	public function getBrowsingToShop()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if($this->request->isPost()){
			$shop_id = $this->request->post('shop_id');
			$shop_id ? '':($this->error(__('Invalid parameters')));
			$list = model('app\api\model\wanlshop\Record')
				->where(['shop_id' => $shop_id, 'user_id' => $this->auth->id])
				->group('goods_id')
				->field('goods_id, createtime')
				->select();
			foreach ($list as $row) {
				// 1.0.8升级
				$row->goods ? $row->goods->visible(['id', 'image', 'title', 'price']) : false;
			}
			$this->success(__('发送成功'), $list);
		}
		$this->error(__('非法请求'));
	}

	/**
	 * 获取商品评论
	 *
	 * @ApiSummary  (WanlShop 获取商品下所有评论)
	 * @ApiMethod   (POST)
	 *
	 * @param string $tag 评论分类
	 * @param string $id  商品ID
	 * @param string $list_rows  每页数量
	 * @param string $page  当前页
	 */
	public function comment()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$id = $this->request->request("id");
		$tag = $this->request->request('tag');
		// 是否传入商品ID
		$id ? $id : ($this->error(__('非正常访问')));
		// 加载商品模型
		$goodsCommentModel = model('app\api\model\wanlshop\GoodsComment')->order('createtime desc');
		//查询tag 评价:0=好评,1=中评,2=差评
		if($tag){
			if($tag == 'good'){
				$where['state'] = 0;
			}else if($tag == 'pertinent'){
				$where['state'] = 1;
			}else if($tag == 'poor'){
				$where['state'] = 2;
			}else if($tag == 'figure'){
				$where['images'] = ['neq', ''];//有图
			}else{
				$where['tag'] = $tag;
			}
		}
		$where['goods_id'] = $id;
		$where['order_type'] = 'goods';
		$comment['comment'] = $goodsCommentModel
//            ->alias('comment')
//			->with(['user'])
			->where($where)
			->paginate();
        foreach ($comment['comment'] as &$item){
            $item['user'] = User::where('id',$item['user_id'])->find();
        }
		// $comment['tag'] = array_count_values($goodsCommentModel->where(['goods_id'=>$id])->limit(100)->column('tag')); //统计热词
		foreach ($comment['comment'] as $row) {
			$row->getRelation('user')->visible(['username','nickname','avatar']);
		}
		$goods = model('app\api\model\wanlshop\Goods')
			->where(['id' => $id])
			->find();
		// 1.1.6升级 兼容php7.4
		if($goods){
			$comment['statistics'] = [
				'rate'     => $goods['comment'] == 0 ? '0' : bcmul(bcdiv($goods['praise'], $goods['comment'], 2), 100, 2),
				'total'    => $goods['comment'],
				'good'     => $goods['praise'],
				'pertinent'=> $goods['moderate'],
				'poor'     => $goods['negative'],
				'figure'   => $goodsCommentModel->where(['goods_id' => $id])->where('images','neq', '')->count()
			];
		}else{
			$comment['statistics'] = [];
		}

		$this->success('返回成功', $comment);
	}

	/**
	 * 获取运费模板和子类 内部方法 -----下个版本完善------
	 * @param string $id  运费ID
	 * @param string $weigh  商品重量
	 * @param string $city  邮递城市
	 * @param string $number  商品数量
	 */
	private function freight($id = null, $weigh = 0, $city = '北京', $number = 1)
	{
		// 运费模板
		$data = model('app\api\model\wanlshop\ShopFreight')->where('id', $id)->field('id,delivery,isdelivery,name,valuation')->find();
        if($data){
            $data['price'] = 0;

            // 是否包邮:0=自定义运费,1=卖家包邮
            if($data['isdelivery'] == 0){
                // 获取地址编码 1.1.0升级
                $list = model('app\api\model\wanlshop\ShopFreightData')
                    ->where([
                        ['EXP', Db::raw('FIND_IN_SET('.model('app\common\model\Area')->get(['name' => $city])->id.', citys)')],
                        'freight_id' => $id
                    ])
                    ->find();
                // 查询是否存在运费模板数据
                if(!$list){
                    $list = model('app\api\model\wanlshop\ShopFreightData')->get(['freight_id' => $id]);
                }

                // 计价方式:0=按件数,1=按重量,2=按体积
                if($data['valuation'] == 0){
                    if($number <= $list['first']){
                        $price = $list['first_fee'];
                    }else{
                        $price = ceil(($number - $list['first']) / $list['additional']) * $list['additional_fee'] + $list['first_fee'];
                    }
                }else{
                    $weigh = $weigh * $number; // 订单总重量
                    if($weigh <= $list['first']){ // 如果重量小于等首重，则首重价格
                        $price = $list['first_fee'];
                    }else{
                        $price = ceil(($weigh - $list['first']) / $list['additional']) * $list['additional_fee'] + $list['first_fee'];
                    }
                }
                $data['price'] = $price;
            }
        }else{
            $data['price'] = 0;

        }

		return $data;
	}

	/**
	 * 查询我的优惠券 内部方法 (跨段存在登录问题，无法解决，暂时复制进来这个方法)
	 *
	 * @param string $goods_id 商品ID
	 * @param string $shop_id 店铺ID
	 * @param string $shop_category_id 分类ID
	 * @param string $price 价格
	 */
	private function queryCoupon($goods_id = null, $shop_id = null, $shop_category_id = null, $price = null)
	{
		$user_coupon = [];
		if ($this->auth->isLogin()) {
			foreach (model('app\api\model\wanlshop\CouponReceive')->where([
				'user_id' => $this->auth->id,
				'shop_id' => $shop_id,
				'limit' => ['<=', intval($price)],
				'state' => '1'
			])->select() as $row) {
				$user_coupon[$row['coupon_id']] = $row;
			}
		}
		// 开始查询
		$list = [];
		$goods_id = explode(",",$goods_id);
		$shop_category_id = explode(",",$shop_category_id);
		//要追加一个排序 选出一个性价比最高的
		foreach (model('app\api\model\wanlshop\Coupon')->where([
			'shop_id' => $shop_id,
			'limit' => ['<=', intval($price)]
		])->select() as $row) {
			// 筛选出还未开始的
			if(!($row['pretype'] == 'fixed' && (strtotime($row['startdate']) >= time() || strtotime($row['enddate']) < time()))){
				//追加字段
				$row['choice'] = false;
				// 检查指定的键名是否存在于数组中
				if(array_key_exists($row['id'], $user_coupon)){
					$row['invalid'] = 0; // 强制转换优惠券状态
					$row['id'] = $user_coupon[$row['id']]['id'];
					$row['state'] = true;
				}else{
					$row['state'] = false;
				}
				// 排除失效优惠券
				if($row['invalid'] == 0){
					// 高级查询，比较数组，返回交集如果和原数据数目相同则加入
					if($row['rangetype'] == 'all'){
						$list[] = $row;
					}
					if($row['rangetype'] == 'goods' && count($goods_id) == count(array_intersect($goods_id, explode(",",$row['range'])))){
						$list[] = $row;
					}
					// 1.1.0升级
					if($row['rangetype'] == 'category'){
						// 判断优化全类目是否在商品类目中，explode(',', $row['range'])[0] 目的向前兼容
						if( in_array(explode(',', $row['range'])[0], $shop_category_id) ){
							$list[] = $row;
						}
					}
				}
			}
		}
		return $list;
	}



	/**
	 * 生成查询所需要的条件,排序方式
	 * @param mixed   $searchfields   快速查询的字段
	 * @param boolean $relationSearch 是否关联查询
	 * @return array
	 */
	protected function buildparams($searchfields = null, $relationSearch = null,$name=null)
	{
	    $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
	    $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
		// 获取传参
	    $search = $this->request->get("search", '');
	    $filter = $this->request->get("filter", '');
	    $op = $this->request->get("op", '', 'trim');
	    $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
	    $order = $this->request->get("order", "DESC");
	    $filter = (array)json_decode($filter, true);
	    $op = (array)json_decode($op, true);
	    $filter = $filter ? $filter : [];
	    $where = [];
	    $tableName = '';
	    if ($relationSearch) {
	        if (!empty($this->model)) {
	            $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
	            $name = $this->model->getTable();
	            $tableName = $name . '.';
	        }
            if($name){
                $tableName = $name . '.';
            }
	        $sortArr = explode(',', $sort);
	        foreach ($sortArr as $index => & $item) {
	            $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
	        }
	        unset($item);
	        $sort = implode(',', $sortArr);
	    }


		// 判断是否需要验证权限
		// if (!$this->auth->match($this->noNeedLogin)) {
		//     $where[] = [$tableName . 'user_id', 'in', $this->auth->id];
		// }

	    if ($search) {
	        $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
	        foreach ($searcharr as $k => &$v) {
	            $v = stripos($v, ".") === false ? $tableName . $v : $v;
	        }
	        unset($v);
	        $arrSearch = [];
	        foreach (explode(" ", $search) as $ko) {
	        	$arrSearch[] = '%'.$ko.'%';
	        }
	        $where[] = [implode("|", $searcharr), "LIKE", $arrSearch];
	    }
		// 历遍所有
		if (array_key_exists('category_id', $filter)) {
			$filter['category_id'] = implode(',', array_column(Tree::instance()->init(model('app\api\model\wanlshop\Category')->all())->getChildren($filter['category_id'], true), 'id'));
		}
	    foreach ($filter as $k => $v) {
	        $sym = isset($op[$k]) ? $op[$k] : '=';
	        if (stripos($k, ".") === false) {
	            $k = $tableName . $k;
	        }
	        $v = !is_array($v) ? trim($v) : $v;
	        $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
	        switch ($sym) {
	            case '=':
	            case '<>':
	                $where[] = [$k, $sym, (string)$v];
	                break;
	            case 'LIKE':
	            case 'NOT LIKE':
	            case 'LIKE %...%':
	            case 'NOT LIKE %...%':
	                $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
	                break;
	            case '>':
	            case '>=':
	            case '<':
	            case '<=':
	                $where[] = [$k, $sym, intval($v)];
	                break;
	            case 'FINDIN':
	            case 'FINDINSET':
	            case 'FIND_IN_SET':
	                $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
	                break;
	            case 'IN':
	            case 'IN(...)':
	            case 'NOT IN':
	            case 'NOT IN(...)':
	                $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
	                break;
	            case 'BETWEEN':
	            case 'NOT BETWEEN':
	                $arr = array_slice(explode(',', $v), 0, 2);
	                if (stripos($v, ',') === false || !array_filter($arr)) {
	                    continue 2;
	                }
	                //当出现一边为空时改变操作符
	                if ($arr[0] === '') {
	                    $sym = $sym == 'BETWEEN' ? '<=' : '>';
	                    $arr = $arr[1];
	                } elseif ($arr[1] === '') {
	                    $sym = $sym == 'BETWEEN' ? '>=' : '<';
	                    $arr = $arr[0];
	                }
	                $where[] = [$k, $sym, $arr];
	                break;
	            case 'RANGE':
	            case 'NOT RANGE':
	                $v = str_replace(' - ', ',', $v);
	                $arr = array_slice(explode(',', $v), 0, 2);
	                if (stripos($v, ',') === false || !array_filter($arr)) {
	                    continue 2;
	                }
	                //当出现一边为空时改变操作符
	                if ($arr[0] === '') {
	                    $sym = $sym == 'RANGE' ? '<=' : '>';
	                    $arr = $arr[1];
	                } elseif ($arr[1] === '') {
	                    $sym = $sym == 'RANGE' ? '>=' : '<';
	                    $arr = $arr[0];
	                }
	                $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
	                break;
	            case 'LIKE':
	            case 'LIKE %...%':
	                $where[] = [$k, 'LIKE', "%{$v}%"];
	                break;
	            case 'NULL':
	            case 'IS NULL':
	            case 'NOT NULL':
	            case 'IS NOT NULL':
	                $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
	                break;
	            default:
	                break;
	        }
	    }
	    $where = function ($query) use ($where) {
	        foreach ($where as $k => $v) {
	            if (is_array($v)) {
	                call_user_func_array([$query, 'where'], $v);
	            } else {
	                $query->where($v);
	            }
	        }
	    };
	    return [$where, $sort, $order];
	}
    public function groupsList()
    {
        $title = $this->request->request("title",'');
        $is_special_offer = $this->request->request("is_special_offer",'0');
        $is_team_leader = $this->request->request("is_team_leader",'0');
        $paginate = $this->request->request("paginate",10);
//        $goodsModel = model('app\api\model\wanlshop\Goods');
        $goodsModel = model('app\api\model\wanlshop\Goods')->alias('goods');
        $goodsModel->where('goods.activity_type', 'newGroups')

            ->where('goods.status', '=', 'normal'); // 指定goods表的status列
        if ($title) {
            $goodsModel->where('goods.title', 'like', '%' . $title . '%');  // 指定goods表的title列
        }
        if($is_special_offer){
            $goodsModel->where('is_special_offer',  $is_special_offer);
        }
        if($is_team_leader){
            $goodsModel->where('is_team_leader',  $is_team_leader);
        }else{
            $goodsModel->where('is_team_leader', 0);
        }
        $list = $goodsModel->order('createtime','DESC')->paginate($paginate);
        foreach ($list as &$value) {
            $shop = model('app\api\model\wanlshop\Shop')->where('id', $value['shop_id'])->find();
            $shop['isFollow'] = model('app\api\model\wanlshop\find\Follow')
                ->where([
                    'user_no' => $shop['find_user']['user_no'],
                    'user_id' => $this->auth->id
                ])
                ->count();
            // 将 shop 数据赋值回去
            $value['shop'] = $shop;
            $userModel = model('app\api\model\User');
            $value['sales'] = $userModel->alias('u')
                ->join('wanlshop_order o', 'u.id = o.user_id')
                ->join('wanlshop_order_goods og', 'o.id = og.order_id')
                ->where('og.goods_id', $value['id'])
                ->count();
        }
        $this->success('返回成功', $list);
    }
    //跟团记录
    public function buyGroupList()
    {
        $good_id = $this->request->request("good_id",'');
        $userModel = model('app\api\model\User');
        $paginate = $this->request->request("paginate",10);
        $users = $userModel->alias('u')
            ->join('wanlshop_order o', 'u.id = o.user_id')
            ->join('wanlshop_order_goods og', 'o.id = og.order_id')
            ->where('og.goods_id', $good_id)
            ->field('u.*, o.*, og.*, o.createtime as order_create_time')
            ->paginate($paginate);
        foreach ($users as &$user) {
            $user['order_create_time'] = date('Y-m-d H:i:s',$user['order_create_time']);
        }
        $this->success('返回成功', $users);
    }
    //分享海报
    public function groupShareImg()
    {
        $good_id = $this->request->request("good_id", '');
        $publicPath = realpath(ROOT_PATH . 'public') . DIRECTORY_SEPARATOR;
        // 商品信息
        $goodsModel = model('app\api\model\wanlshop\Goods')->where('id', $good_id)->find();
        // 商品价格
        $GoodsSku = model('app\api\model\wanlshop\GoodsSku')->where('goods_id', $good_id)->where('state',0)->order('id','desc')->find();
        // 用户信息
        $user = \app\admin\model\User::where('id', $this->auth->id)->find();
        // 加载背景图
        $background = imagecreatefrompng($publicPath . 'back/back.png');
        $bg_width = imagesx($background);
        $bg_height = imagesy($background);

        // 加载用户头像并制作圆形头像
//        $avatar_image = imagecreatefromjpeg($publicPath . $user['avatar']?$user['avatar']:$goodsModel['image']);
        $avatar_url = $user['avatar'];
        if(!$avatar_url){
            $avatar_url = '/uploads/20240817/ad68a1c50a64cce9dbdb3ce3133deb93.png';
        }
        // 检查 $user['avatar'] 是否包含域名
        if(!is_file(ROOT_PATH.'public'.$avatar_url)){
            $avatar_url = $this->down_img($avatar_url);
            \app\common\model\User::update(['avatar'=>$avatar_url],['id'=>$this->auth->id]);
            $avatar_url = ROOT_PATH.'public'.$avatar_url;
        }else{
            $avatar_url = ROOT_PATH.'public'.$avatar_url;
        }
        $mime_type = mime_content_type($avatar_url);
        if ($mime_type === 'image/jpeg') {
            $avatar_image = imagecreatefromjpeg($avatar_url);
        } elseif ($mime_type === 'image/png') {
            $avatar_image = imagecreatefrompng($avatar_url);
        }
        $avatar_image = imagescale($avatar_image, 60, 60); // Resize to 60x60

        // 创建圆形掩码
        $mask = imagecreatetruecolor(60, 60);
        $transparent = imagecolorallocatealpha($mask, 0, 0, 0, 127);
        imagefill($mask, 0, 0, $transparent);
        imagealphablending($mask, false);
        imagesavealpha($mask, true);

        $black = imagecolorallocate($mask, 0, 0, 0);
        imagefilledellipse($mask, 30, 30, 60, 60, $black);

        $final_avatar = imagecreatetruecolor(60, 60);
        imagealphablending($final_avatar, false);
        imagesavealpha($final_avatar, true);

        $transparent = imagecolorallocatealpha($final_avatar, 0, 0, 0, 127);
        imagefill($final_avatar, 0, 0, $transparent);

        for ($x = 0; $x < 60; $x++) {
            for ($y = 0; $y < 60; $y++) {
                $alpha = (imagecolorat($mask, $x, $y) >> 24) & 0x7F;
                $color = imagecolorat($avatar_image, $x, $y);
                $color = imagecolorsforindex($avatar_image, $color);
                $color = imagecolorallocatealpha($final_avatar, $color['red'], $color['green'], $color['blue'], $alpha);
                imagesetpixel($final_avatar, $x, $y, $color);
            }
        }

        // 将圆形头像复制到背景图像
        imagecopy($background, $final_avatar, 20, 20, 0, 0, imagesx($final_avatar), imagesy($final_avatar));

        // 添加用户名称（黄色 #333333）
        $text_color = imagecolorallocate($background, 51, 51, 51);
        $font_path = $publicPath . 'back/msyh.ttf';
        imagettftext($background, 16, 0, 90, 45, $text_color, $font_path, $user['nickname']);

        // 添加用户描述（灰色 #999999）
        $desc_color = imagecolorallocate($background, 153, 153, 153);
        imagettftext($background, 12, 0, 90, 70, $desc_color, $font_path, $goodsModel['title']);

        // 加载商品图片，缩放并添加到背景图

        $mime_type = mime_content_type($publicPath . $goodsModel['image']);
        if ($mime_type === 'image/jpeg') {
            $product_image = imagecreatefromjpeg($publicPath . $goodsModel['image']);
        } elseif ($mime_type === 'image/png') {
            $product_image = imagecreatefrompng($publicPath . $goodsModel['image']);
        }
        $product_image = imagescale($product_image, 260, 210);
        imagecopy($background, $product_image, 20, 100, 0, 0, imagesx($product_image), imagesy($product_image));

        // 商品标题处理
        $title = $goodsModel['title'];
        if (mb_strlen($title) > 6) {
            $title = mb_substr($title, 0, 6) . '...';
        }

        // 添加商品标题（黑色 #333333）
        $title_color = imagecolorallocate($background, 51, 51, 51);
        imagettftext($background, 14, 0, 20, 340, $title_color, $font_path, $title);

        // 添加商品价格（红色 #DD0A2C）
        $price_color = imagecolorallocate($background, 221, 10, 44);
        imagettftext($background, 20, 0, 20, 390, $price_color, $font_path, '¥' . $GoodsSku['price']);
        // 添加提示信息（灰色 #999999）
        $desc_color = imagecolorallocate($background, 153, 153, 153);
        imagettftext($background, 10, 0, 20, 420, $desc_color, $font_path, '长按识别或扫，扫描二维码');
        // 生成二维码
        $url = 'https://c.hrbyuecai.com/tuangou/#/pages/productDetail/productDetail?id=' . $good_id.'&type=xuanfu';
        QRcode::png($url, $publicPath . 'back/qrcode.png');
        $qr_image = imagecreatefrompng($publicPath . 'back/qrcode.png');
        $qr_image = imagescale($qr_image, 100, 100); // Resize QR code
        imagecopy($background, $qr_image, $bg_width - imagesx($qr_image) - 20, $bg_height - imagesy($qr_image) - 20, 0, 0, imagesx($qr_image), imagesy($qr_image));

        // 捕获输出到缓冲区
        ob_start();
        imagepng($background);
        $image_data = ob_get_contents();
        ob_end_clean();

        // 清理图像资源
        imagedestroy($background);
        imagedestroy($product_image);
        imagedestroy($qr_image);
        imagedestroy($avatar_image);
        imagedestroy($final_avatar);
        imagedestroy($mask);


//        $base64_image = base64_encode($image_data);
        $time = 'share'.time();
        $savePath = $publicPath . 'share/'.$time.'.png';
        // 将图像数据保存到服务器
        file_put_contents($savePath,$image_data);
        $this->success('返回成功', 'share/'.$time.'.png');
    }
    //自提点/门店列表
    public function spotList()
    {
        $good_id = $this->request->request("good_id", '');
        $pointLat = (float)$this->request->request("pointLat", '');
        $pointLng = (float)$this->request->request("pointLng", '');
        $goodWhere = ['id' => ['in', $good_id]];
        $goodsModel = model('app\api\model\wanlshop\Goods')->where($goodWhere)->select();
        $deliveryFound = false;
        $addressSpots = [];

        foreach ($goodsModel as $goods) {
            if ($goods['delivery_method'] == 1) {
                $deliveryFound = true;
            }
            //自提店
            if ($goods['delivery_method'] == 2) {
                // 合并自提点 ID
                $selfAddressSpots = explode(',', $goods['self_address_spot_id']);
                $platformAddressSpots = explode(',', $goods['platform_address_spot_id']);
                $addressSpots = array_merge($addressSpots, $selfAddressSpots, $platformAddressSpots);
            }
            if ($goods['delivery_method'] == 3) {
                // 合并自提点 ID
                $selfAddressSpots = explode(',', $goods['self_address_spot_id']);
//                $platformAddressSpots = explode(',', $goods['platform_address_spot_id']);
                $addressSpots = array_merge($addressSpots, $selfAddressSpots);
            }
        }

        if ($deliveryFound) {
            $this->error('一件代发的商品不能选择');
        }
        // 去重
        $addressSpots = array_unique($addressSpots);
        if(count($goodsModel) > 1) {
            $spotCounts = array_count_values($addressSpots);
            // 提取重复的自提点 ID（出现次数超过1次）
            $addressSpots = array_keys(array_filter($spotCounts, function($count) {
                return $count > 1;
            }));
        }
        // 根据自提点 ID 查询
        $where = ['id' => ['in', $addressSpots]];
        $query = AddressSpot::where($where);

        $distance = 2000; // 5 km
        $earthRadius = 6371;
        $results = $query->select();
//        halt($results);
        foreach ($results as $k=>&$v){
            if(!empty($pointLat)&&!empty($pointLng)){

                $gap_km = $this->distance($pointLat,$pointLng,$v['pointLat'],$v['pointLng']);

                $v['gap_km'] = sprintf('%.1f',$gap_km);
            }else{
                $v['gap_km'] = 0;
            }

        }
        $this->success('返回成功', $results);
    }

    public function distance($lat1, $lon1, $lat2, $lon2) {
        $earth_radius = 6371; // 地球半径，单位为千米

        $dlat = deg2rad($lat2 - $lat1);
        $dlon = deg2rad($lon2 - $lon1);

        $a = sin($dlat/2) * sin($dlat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dlon/2) * sin($dlon/2);
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));

        $distance = $earth_radius * $c;

        return $distance;
    }
    public function industry()
    {
       $industry = Industry::where('level',1)->select();
       $datas = [];
       $data = [];
       foreach ($industry as $keys=>$item){
           $data[$keys]['value'] = $item['id'];
           $data[$keys]['text'] =  $item['industry_name'];
           $ins = Industry::where('level',2)->where('par_id',$item['id'])->select();
           $children = [];
           foreach ($ins as $key=>$in){
               $children[$key]['value'] = $in['id'];
               $children[$key]['text'] =  $in['industry_name'];
           }
           $data[$keys]['children'] = $children ;

       }
        $this->success('返回成功', $data);
    }
    //查询是否是团长
    public function isTeam(){
	    $phone = $this->auth->mobile;
	    $spot = AddressSpot::where('phone',$phone)->select();
	    if(count($spot)>0){
            $this->success('返回成功', 1);
        }else{
            $this->success('返回成功', 0);
        }
    }
    public function qrcodelog()
    {
        $params = $this->request->param();
        $where = [];
        if(!empty($params['spot_id'])){

            $where['wanlshop_order.spot_id'] = ['=',$params['spot_id']];
        }
        if(!empty($params['time'])){
            $time = explode(',',$params['time']);
            // 构造开始时间和结束时间的字符串
            $startDateTime = $time[0] . ' 00:00:00';
            $endDateTime = $time[1] . ' 23:59:59';

            // 将时间字符串转换为时间戳
            $startTime = strtotime($startDateTime);
            $endTime = strtotime($endDateTime);
            // 在 where 条件中使用时间戳
            $where['log.createtime'] = ['between time', [$startTime, $endTime]];
        }
//        halt($where);
        $qrcodeLogs = QrcodeLog::
            alias('log')
            ->where('log.user_id',$this->auth->id)
            ->join('wanlshop_qrcode','wanlshop_qrcode.id=log.qrcode_id',"left")
            ->join('wanlshop_order','wanlshop_order.id=wanlshop_qrcode.order_id',"left")
            ->where($where)
            ->order('log.createtime','DESC')
            ->paginate(10);
        foreach ($qrcodeLogs as &$qrcodeLog){
            $qrcode = \app\api\model\wanlshop\Qrcode::where('id',$qrcodeLog['qrcode_id'])->find();
            $order = \app\api\model\wanlshop\Order::where('id',$qrcode['order_id'])->find();
            $shop = \app\admin\model\wanlshop\Shop::where('id',$order['shop_id'])->find();
            $goods = OrderGoods::where('order_id',$order['id'])->find();
            $qrcodeLog['qrcode'] = $qrcode;
            $qrcodeLog['order'] = $order;
            $qrcodeLog['shop'] = $shop;
            $qrcodeLog['goods'] = $goods;
        }
        $this->success('返回成功', $qrcodeLogs);
    }

    public function category()
    {
        $list = \app\admin\model\wanlshop\Category::where(['pid'=>0,'type'=>'goods'])->select();
        $this->success('一级分类',$list);
    }

    public function down_img($url, $path = "./download/images/")
    {
        // 因为不知道最后接受到的文件是什么格式，先建立一个临时文件，用于保存
        $tmpFile = tempnam(sys_get_temp_dir(), 'image');

        # 文件下载 BEGIN #

        // 打开临时文件，用于写入（w),b二进制文件
        $resource = fopen($tmpFile, 'wb');
        // 初始化curl
        $curl = curl_init($url);
        // 设置输出文件为刚打开的
        curl_setopt($curl, CURLOPT_FILE, $resource);
        // 不需要头文件
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 执行
        curl_exec($curl);
        // 关闭curl
        curl_close($curl);
        // 关闭文件
        fclose($resource);

        # 文件下载 END #

        // 获取文件类型
        if (function_exists('exif_imagetype')) {
            // 读取一个图像的第一个字节并检查其签名(这里需要打开mbstring及php_exif)
            $fileType = exif_imagetype($tmpFile);
        } else {
            // 获取文件大小，里面第二个参数是文件类型 （这里后缀可以直接通过getimagesize($url)来获取，但是很慢）
            $fileInfo = getimagesize($tmpFile);
            $fileType = $fileInfo[2];
        }
        // 根据文件类型获取后缀名
        $extension = image_type_to_extension($fileType);
        // 计算指定文件的 MD5 散列值，作为保存的文件名，重复下载同一个文件不会产生重复保存，相同的文件散列值相同
        $md5FileName = md5_file($tmpFile);
        // 最终保存的文件
        $returnFile = $path . $md5FileName . $extension;
        // 检查传过来的路径是否存在，不存在就创建
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        // 复制临时文件到最终保存的文件中
        copy($tmpFile, $returnFile);
        // 释放临时文件
        @unlink($tmpFile);
        // 返回保存的文件路径
        return ltrim($returnFile,'.');
    }
    //团购结束自动下架
    public function offShelf(){
        $currentDateTime = date('Y-m-d H:i:s');
        $goods = Goods::where('activity_type', 'newGroups')
            ->where('group_end_time', '<', $currentDateTime)
            ->update(['status' => 'hidden']);
        $this->success('返回成功', $goods);
    }
    //获取积分商品列表
    public function scoreList()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $goodsModel  = model('app\api\model\wanlshop\Goods');
        // 生成搜索条件
        list($where, $sort, $order) = $this->buildparams('title,category.name',true,'goods');
        $shopIdFiltered = false;
        $filter = $this->request->get("filter", '');
        $type = $this->request->get("type", 0);
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];
        if (isset($filter['shop_id']) && !empty($filter['shop_id'])) {
            $shopIdFiltered = true;
        }
        //获取1积分抵扣金额
        $config = get_addon_config('wanlshop');
        $deduct_amount = $config['config']['deduction_amount']; // 1积分抵扣金额
        // 查询数据
        $list = $goodsModel
            ->alias('goods')
            ->with(['shop','category'])
            ->where($where)
            ->where('goods.status', 'normal')
            ->where('goods.integral_status', 1)
            ->where('goods.is_integral', 1)
            ->order($sort, $order);
        if($type == 1){
            $list->where('maximum_proportion','<>',100);
        }else{
            $list->where('maximum_proportion',100);
        }

        $list = $list->paginate();
        foreach ($list as $row) {
            $sku =  GoodsSku::where('goods_id',$row['id'])->find();
            $row->stock = $sku['stock'];
            $row->getRelation('shop')->visible(['city', 'shopname', 'state', 'isself']);
            $row->getRelation('category')->visible(['id','pid','name']);
            $row->isLive = model('app\api\model\wanlshop\Live')->where(['shop_id' => $row['shop_id'], 'state' => 1])->field('id')->find();
            // 积分可抵扣金额的百分比
            $maximum_proportion = $row['maximum_proportion'] / 100;
            // 商品的价格
            $price = $row['price'];
            // 最大可以使用积分抵扣的金额
            $max_deductible_amount = min($price, $price * $maximum_proportion);
            // 需要使用的积分数 = 最大可抵扣金额 ÷ 每1积分可抵扣的金额
            $required_score = ceil($max_deductible_amount / $deduct_amount);
            // 实际抵扣金额 = 所使用的积分 * 每1积分可抵扣的金额
            $actual_deduct_amount = $required_score * $deduct_amount;
            // 保证抵扣后剩余金额是非负，并保留两位小数
            $remaining_price = number_format($price - $actual_deduct_amount, 2, '.', '');
            // 设置使用积分和最终价格
            $row->useScore = $required_score;
            $row->price = $remaining_price;
        }
        $this->success('返回成功', $list);
    }

}
